/**
 * 区域tree筛选器
 */
import React, { useEffect, useState } from "react";
import { Form, TreeSelect } from "antd";

import request from "@/utils/request";

import type { FormItemProps } from "antd/es/form";
import type { TreeSelectProps } from "antd/es/tree-select";

export interface ResourceTreeSelectProps {
	formItemProps?: FormItemProps;
	childProps?: TreeSelectProps;

	onQueryDataSuccess?(data: TreeData): void;

	onQueryChildDataSuccess?(key: React.Key, data: TreeData): void;
}

const ResourceTreeSelect: React.FC<ResourceTreeSelectProps> = ({
	formItemProps = {},
	childProps = {},
	onQueryDataSuccess,
	onQueryChildDataSuccess
}) => {
	const [key, setKey] = useState(0);
	const [treeData, setTreeData] = useState<DataNode[]>([]);

	useEffect(() => {
		if (childProps.treeData) {
			setKey(key => key + 1);
			setTreeData(childProps.treeData as DataNode[]);
		}
	}, [childProps.treeData]);

	useEffect(() => {
		if (!treeData?.length && !childProps.treeData) {
			queryResourceTree();
		}
	}, [treeData, childProps.treeData]);

	const updateTreeData = (list: DataNode[], key: React.Key, children: DataNode[]): DataNode[] =>
		list.map(node => {
			if (node.key === key) {
				return {
					...node,
					children
				};
			}
			if (node.children) {
				return {
					...node,
					children: updateTreeData(node.children, key, children)
				};
			}
			return node;
		});

	const queryResourceTree = () => {
		request("resourceTree", { data: {
			tenantId: 1
			} }).then(res => {
			if (res?.code === 0 && res.data) {
				setTreeData([{ value: 0, label: "==根目录==" }, ...res.data]);
				onQueryDataSuccess?.(res.data);
			}
		});
	};

	return (
		<Form.Item {...formItemProps}>
			<TreeSelect
				showSearch
				allowClear
				key={key}
				// showCheckedStrategy={TreeSelect.SHOW_PARENT}
				placeholder="请选择"
				treeNodeFilterProp="title"
				treeDefaultExpandAll={false}
				dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
				{...childProps}
				treeData={treeData}
			/>
		</Form.Item>
	);
};

export default ResourceTreeSelect;
